var request = require('request');
var cheerio = require('cheerio'); 
var fs = require('fs');
let url = "http://pic.netbian.com"
var options = {
    url: url+"/4kdongman/index.html",
};
let data=[];
let max = 147;
let start = 1;
console.log("第一次爬取开始了--------");
function callback(error, response, body) {
let $=cheerio.load(body)
     if(response.statusCode==200){        
			 let off = true;
			 $(".slist .clearfix img").map((index,item)=>{
				 data.push({img:url+$(item)[0].attribs.src,alt:`${start}__${index+1}___壁纸`});
			 })
			 // 页脚
			 $(".page a").map((index,item)=>{
				let search = $(item)[0].attribs.href.search("_");
				let number = $(item)[0].attribs.href.slice(search+1);
				let nub = parseInt(number.split(".")[0]);
				if(off){
					if(nub>start){
						off = false;
						start = nub
						if(start<=max){
							request({url:`${url}/4kdongman/index_${start}.html`}, callback);
							console.log(`第${start}次--爬取-----开始了`)
							console.log(`爬取地址：${url}/4kdongman/index_${start}.html-------爬取的次数：${start}次`);
							console.log('爬取到：',$(".slist .clearfix img").length)
							if(start == max){
								 txt(data);
							}
						}
					}	
				}else{
					return true ;
				}
			 })
	
     }else{
		return false ;
     }
}
request(options, callback);



// 创建文件
function txt(infos){
	console.log('正在写入······················');
    if(infos){
            fs.writeFile('./index.json',JSON.stringify(infos),function (err) {
                if (err) {
                    console.log('写入数据失败········');
                } else {
                    console.log('写入数据成功········');
                }
            })        
        }
}
